package com.luojialong.onlineJudge.controller;


import cn.hutool.http.ContentType;
import com.luojialong.onlineJudge.common.BaseResponse;
import com.luojialong.onlineJudge.common.ErrorCode;
import com.luojialong.onlineJudge.common.ResultUtils;
import com.luojialong.onlineJudge.exception.BusinessException;
import com.luojialong.onlineJudge.model.dto.file.FileSearchRequest;
import com.luojialong.onlineJudge.service.UserService;
import com.luojialong.onlineJudge.utils.MinioUtils;
import com.google.common.net.HttpHeaders;
import io.minio.GetObjectResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ContentDisposition;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * 文件的上传和下载
 *
 * @author 罗家龙
 */
@Controller
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;


    @Resource
    private MinioUtils minioService;


    /**
     * @param fileSearchRequest 文件查看请求
     * @param response          想前端传输要查看的文件
     * @功能描述 下载文件:
     */
    @GetMapping("/watch")
    @ResponseBody
    public void download(FileSearchRequest fileSearchRequest, HttpServletResponse response) {
        try {
            GetObjectResponse outResponse = minioService.getObject(fileSearchRequest);
            // 获取文件后缀名
            log.info("文件名为:" + fileSearchRequest.getFileName());

            byte[] buffer = new byte[outResponse.available()];

            outResponse.read(buffer);
            // 清空response
            response.reset();
            // 文件类型
            response.setContentType(ContentType.OCTET_STREAM.getValue());
            // 文本类型文件的编码
            response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
            // 文件长度
            response.setContentLength(buffer.length);
            // 文件的处理方式。attachment 表示附件，filename 表示文件的名称
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()    // 附件形式
                    .filename(fileSearchRequest.getFileName(), StandardCharsets.UTF_8)  // 文件名称 & 编码
                    .build().toString());
            response.getOutputStream().write(buffer);
            response.getOutputStream().flush();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "文件操作异常");
        }
    }


    //upload
    @PostMapping("/upload")
    @ResponseBody
    public BaseResponse<String> upload(@RequestPart("multipartFile") MultipartFile multipartFile, String fileParentPath, HttpServletRequest request) throws Exception {
        System.out.println(fileParentPath);
        System.out.println(multipartFile.getOriginalFilename());
        if (multipartFile.isEmpty()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "文件上传失败,网络问题");
        }
        Long id = userService.getLoginUser(request).getId();
        String res = minioService.uploadObject(multipartFile, id, fileParentPath);
        minioService.isObjectExist(res);
        String url = minioService.getUrl(res);
        return ResultUtils.success(url);
    }


}
